package com.xyz.gulimall.product.service.impl;

import com.xyz.gulimall.product.entity.AttrEntity;
import com.xyz.gulimall.product.service.AttrService;
import com.xyz.gulimall.product.vo.AttrGroupAttrsVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyz.common.utils.PageUtils;
import com.xyz.common.utils.Query;

import com.xyz.gulimall.product.dao.AttrGroupDao;
import com.xyz.gulimall.product.entity.AttrGroupEntity;
import com.xyz.gulimall.product.service.AttrGroupService;

import javax.annotation.Resource;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {


    @Resource
    AttrService attrService;

     @Override
     public PageUtils queryPage(Map<String, Object> params) {
              IPage<AttrGroupEntity> page = this.page(
                      new Query<AttrGroupEntity>().getPage(params),
                      new QueryWrapper<AttrGroupEntity>()
              );
              return new PageUtils(page);
     }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        String key = (String)params.get("key");
        QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>();
        if(!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_group_id",key).or().like("attr_group_name",key);
            });
        }
        if(catelogId == 0){
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);
            return new PageUtils(page);
        }else {

            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params), wrapper.eq("catelog_id",catelogId));
            return new PageUtils(page);
        }
    }

    @Override
    public List<AttrGroupAttrsVo> fandWithattr(Long catId) {
        List<AttrGroupEntity> list = this.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id",catId));
        list.forEach(System.err::println);
        List<AttrGroupAttrsVo> attrGroupAttrsVos = list.stream().map(item -> {
            AttrGroupAttrsVo attrGroupAttrsVo = new AttrGroupAttrsVo();
            BeanUtils.copyProperties(item, attrGroupAttrsVo);
            attrGroupAttrsVo.setAttrs(attrService.getRelationAttr(attrGroupAttrsVo.getAttrGroupId()));
            return attrGroupAttrsVo;
        }).filter((x)->{
            return x.getAttrs()!=null;
        }).collect(Collectors.toList());
        return attrGroupAttrsVos;
    }

}